import os

import yaml

from utils.PathUtil import yaml_path
from utils.LogUtil import logger

class YamlUtil:

    def __init__(self):
        self.yaml_path = yaml_path

    def read_yaml_data(self, yaml_name,sub_dir=None, key_name=None):
        """
        :param yaml_name: yaml文件名
        :param sub_dir: 二级目录
        :param key_name: yaml文件内字段名
        :return:
        """
        file_path = os.path.join(self.yaml_path, sub_dir, yaml_name)
        logger.info(f"尝试读取YAML文件: {file_path}")  # 调试

        if not os.path.exists(file_path):
            logger.error(f"错误: 文件 {file_path} 不存在!")
            return None

        with open(file_path, mode="r", encoding="utf-8") as f:
            try:
                yaml_data = yaml.safe_load(f)
                logger.info(f"读取到的YAML数据: {yaml_data}")  # 调试

                if not yaml_data:
                    logger.warning("警告: YAML文件内容为空!")
                    return None

                if key_name and key_name not in yaml_data:
                    logger.error(f"错误: 键 '{key_name}' 不在YAML文件中!")
                    return None

                return yaml_data.get(key_name) if key_name else yaml_data
            except yaml.YAMLError as exc:
                logger.error(f"YAML解析错误: {exc}")
                return None


    def extract_case(self, file_name, sub_dir=None, key_name=None):
        """
        处理多条用例
        :param file_name: 文件名称
        :param key_name: yaml文件内字段名
        :return:
        """
        case_value = self.read_yaml_data(file_name, sub_dir, key_name)[0]
        # print(case_value)
        new_case = []
        for value in case_value["case_info"]:
            new_case.append({"request_info": case_value["request_info"], "case_info": value})
        return new_case

    def read_extract_yaml_data(self):
        "专门用来读取extract.yaml文件"
        with open(os.path.join(self.yaml_path, "extract.yaml"), mode="r", encoding="utf-8") as f:
            try:
                value = yaml.safe_load(f)
                return value
            except yaml.YAMLError as exc:
                logger.error(exc)

    def write_extract_yaml(self, data):
        with open(os.path.join(self.yaml_path, "extract.yaml"), mode="a", encoding="utf-8") as f:
            try:
                old_data = self.read_extract_yaml_data()
                if old_data:
                    for key, value in data.items():
                        old_data[key] = value
                        self.clear_extract_yaml()
                        yaml.dump(data=old_data, stream=f, allow_unicode=True, sort_keys=False)
                else:
                    yaml.dump(data=data, stream=f, allow_unicode=True, sort_keys=False)
            except yaml.YAMLError as exc:
                logger.error(exc)

    def clear_extract_yaml(self):
        """清理extract.yaml"""
        with open(os.path.join(self.yaml_path, "extract.yaml"), mode='w', encoding='utf8') as f:
            f.truncate()


if __name__ == '__main__':
    print(os.path.join(yaml_path, "user_login_data.yaml"))
    yaml_util = YamlUtil()
    data = yaml_util.read_yaml_data("upload_model_yl_img.yaml", "cg_upload_fm_img")
    print(data)
